package com.purchase.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author saw
 */
public class HttpUtils {

    /**
     * 无参get请求
     *
     * @param headers 请求头
     * @param url   请求连接
     * @return
     */
    public static HttpResponse get(Map<String,String> headers, String url){

        return HttpRequest.get(url)
                    .addHeaders(headers)
                    .charset(StandardCharsets.UTF_8)
                    .timeout(5000)
                    .execute();
    }

    /**
     * 无参get请求
     *
     * @param headers 请求头
     * @param url   请求连接
     * @return
     */
    public static HttpResponse get(Map<String,String> headers, String url, List<HttpCookie> cookies){

        return HttpRequest.get(url)
                .addHeaders(headers)
                .cookie(cookies)
                .charset(StandardCharsets.UTF_8)
                .timeout(5000)
                .execute();
    }

    /**
     * 有参get请求
     *
     * @param headers 请求头
     * @param url   请求连接
     * @param params    参数
     * @return
     */
    public static HttpResponse get(String url,
                                   JSONObject params,
                                   Map<String,String> headers,
                                   List<HttpCookie> cookies){

        return HttpRequest.get(url)
                .addHeaders(headers)
                .cookie(cookies)
                .form(params)
                .charset(StandardCharsets.UTF_8)
                .timeout(5000)
                .execute();
    }

    /**
     * post请求
     *
     * @param headers 请求头，可为空
     * @param url   请求链接
     * @param params  post请求体，可为空
     * @return
     */
    public static HttpResponse post(Map<String,String> headers, String url, JSONObject params){

        return HttpRequest.post(url)
                .addHeaders(headers)
                .form(params)
                .charset(StandardCharsets.UTF_8)
                .timeout(5000)
                .execute();
    }

    /**
     * post请求
     *
     * @param headers 请求头，可为空
     * @param url   请求链接
     * @param params  post请求体，可为空
     * @return
     */
    public static HttpResponse post(Map<String,String> headers, String url,
                                    JSONObject params, List<HttpCookie> cookies){

        return HttpRequest.post(url)
                .addHeaders(headers)
                .cookie(cookies)
                .form(params)
                .charset(StandardCharsets.UTF_8)
                .timeout(5000)
                .execute();
    }
}
